from django.shortcuts import render
from .models import *
from utils.wrapper import *
from django.core.paginator import Paginator
from django.http import JsonResponse
from .functions import *
from django.db import transaction
from django.db.models import Sum


# 服务主页
def server(request):
    try:
        # 获取所有服务类型
        types = ServerType.objects.get_all()
        # 获取预约总数
        total = ServerType.objects.aggregate(Sum('sum'))['sum__sum']
        for t in types:
            if t.sum == 0:
                t.per = 0
            else:
                num = t.sum / total
                t.per = "%.2f%%" %(num*100)
    except:
        pass
    return render(request,"server/server.html",locals())


# 根据类型所有服务页面
def all(request,param):
    try:
        # 根据类型从数据库拿热门服务
        if param == "0":
            title = "热门项目"
            all_servers = HotProject.objects.get_all()
        else:
            # 根据类型获取项目类型
            title = ServerType.objects.get_type_by_id(param).type
            all_servers = HotProject.objects.get_by_type(param)
    except:
        pass
    else:
        # 创建分页器
        paginator = Paginator(all_servers, 8)
        # 获取当前页码
        page_now = get(request, "page", "1")
        # 当前页面商品
        servers = paginator.page(page_now)

    return render(request, "server/all.html", locals())


# 单独服务介绍页面
def one(request,param):
    try:
        # 根据id获取项目
        project = HotProject.objects.get_project_by_id(get(request,"id"))
        # 获取最新两个项目
        new_project_2 = HotProject.objects.get_new_project_2()
    except:
        pass
    return render(request, "server/one.html", locals())


# 预约表单提交
def order_post(request):
    # 创建保存点
    save_point = transaction.savepoint()
    try:
        # 验证数据合法性，存入数据库
        if check_user_order(request):

            ServerOrder.objects.save_order(request)
            # 更新预约数
            ServerType.objects.update_order_sum(request)
            # 提交操作
            transaction.savepoint_commit(save_point)
            return JsonResponse({"ret": 1})
    except:
        # 如果操作出错，滚回去
        transaction.savepoint_rollback(save_point)
        pass

